package hu.home.arb.bwin;

import hu.home.arb.dao.Dao;
import hu.home.arb.entity.Html;
import hu.home.arb.net.Net;

import java.io.IOException;
import java.net.MalformedURLException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.gargoylesoftware.htmlunit.FailingHttpStatusCodeException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlDivision;
import com.gargoylesoftware.htmlunit.html.HtmlListItem;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSpan;

public class Bwin {
	static Logger logger = LogManager.getLogger(Bwin.class.getName());
	static Connection conn;
	
	public Bwin() throws SQLException {
		super();
		conn = Dao.getConnection();
	}

	public void start() throws FailingHttpStatusCodeException, MalformedURLException, IOException, SQLException {
		logger.info("Start");
		
		WebClient webClient = Net.getWebClient();
				
		LinkedHashMap<String, ArrayList<String>> sportOddsType = new LinkedHashMap<String, ArrayList<String>>();
		LinkedHashMap<String, Integer> sportIds = new LinkedHashMap<String, Integer>();
		//soccer
		/*
		sportIds.put("nav-sport-4", 1);
		sportOddsType.put("nav-sport-4", new ArrayList<String>(
			Arrays.asList(
				"cat_359", //2way - who will win
				"cat_190", //double chance
				"cat_30",  //halftime result
				"cat_31",  //number of goals
				"cat_28",  //handicap (3way)
				"cat_192", //goal bet
				"cat_191"  //half time/fulltime
			)	
		));
		*/
		//tennis
		sportIds.put("nav-sport-5", 2);
		sportOddsType.put("nav-sport-5", new ArrayList<String>());
		//basketball
		sportIds.put("nav-sport-7", 3);
		sportOddsType.put("nav-sport-7", new ArrayList<String>());
		//baseball
		sportIds.put("nav-sport-23", 4);
		sportOddsType.put("nav-sport-23", new ArrayList<String>());
		//handball
		sportIds.put("nav-sport-16", 5);
		sportOddsType.put("nav-sport-16", new ArrayList<String>(
			Arrays.asList(
				"cat_86" //halftime
			)
		));
		//volleyball
		sportIds.put("nav-sport-18", 6);
		sportOddsType.put("nav-sport-18", new ArrayList<String>());
		//ice hockey
		sportIds.put("nav-sport-12", 7);
		sportOddsType.put("nav-sport-12", new ArrayList<String>(
			Arrays.asList(
				"cat_230" //double chance
			)
		));
		//american football
		sportIds.put("nav-sport-11", 8);
		sportOddsType.put("nav-sport-11", new ArrayList<String>(
			Arrays.asList(
				"cat_1116" //3way - result
			)
		));
		
		for(Entry<String, ArrayList<String>> entry : sportOddsType.entrySet()) {
			String sportKey = entry.getKey();
			ArrayList<String> oddsTypes = entry.getValue();
			
			//Fő oldal beolvasása
			HtmlPage mainPage = webClient.getPage(BwinConstants.BWIN_MAIN_URL);
			
			//Megkeresi a sportot és a linkjére kattintani
			HtmlListItem li = mainPage.getHtmlElementById(sportKey);
			//logger.info("sport li > " + li.asXml());
			HtmlAnchor a = (HtmlAnchor) li.getElementsByTagName("a").get(0);
			//logger.info("sport a > " + a.asXml());
			HtmlPage sportPage = a.click();		
			webClient.waitForBackgroundJavaScriptStartingBefore(4000);
			
			//A sport eseményekből az összes kiválasztása
			HtmlDivision sportDiv = (HtmlDivision) sportPage.getHtmlElementById("nav-sport-info");
			//logger.info(sportDiv.asXml());
			HtmlSpan selectAllSpan = (HtmlSpan) sportDiv.getByXPath("//span[@class='nav-select-all']").get(0);
			//logger.info("nav-select-all > " + selectAllSpan.asXml());
			HtmlPage sportOddsPage = selectAllSpan.click();		
			webClient.waitForBackgroundJavaScriptStartingBefore(4000);
			
			//piacok kiválasztása, van ami defaultból ki van választva, azt nem választjuk már ki
			//pl: soccer: 3way
		
			for(String oddsType : oddsTypes) {
				if(sportOddsPage.getByXPath("//*[@id='" + oddsType + "']") != null && 
						sportOddsPage.getByXPath("//*[@id='" + oddsType + "']").size() != 0) {
					sportOddsPage = sportOddsPage.getHtmlElementById(oddsType).click();
					webClient.waitForBackgroundJavaScriptStartingBefore(4000);
				}
			}
			
			//oldal feldolgozása
			readPage(sportIds.get(sportKey),  sportOddsPage, webClient);
		}		
	}
	
	public void readPage(Integer sportId, HtmlPage page, WebClient webClient) throws IOException, SQLException {
		//html oldal mentése
		Html html = new Html();
		html.setBookieId(BwinConstants.BWIN_BOOKIE_ID);
		html.setSportId(sportId);
		html.setText(page.getHtmlElementById("markets-container").asXml());
		
		String sql = "insert into html (html_bookie_id, html_sport_id, html_text) values (?, ?, ?)";
		PreparedStatement pstm = conn.prepareStatement(sql);
		pstm.setInt(1, (int) html.getBookieId());
		pstm.setInt(2, (int) html.getSportId());
		pstm.setString(3, html.getText());
		pstm.executeUpdate();
		logger.info("HTML inserted. Timestamp: " + String.valueOf(new Timestamp((new Date()).getTime())) + " Size: " + html.getText().length());
					
		if(page.getByXPath("//*[@id='markets-pager-bottom']") != null && page.getByXPath("//*[@id='markets-pager-bottom']").size() != 0) {
			//Lapozó linkek kigyűjtése
			HtmlDivision marketPagerBottom = (HtmlDivision) page.getHtmlElementById("markets-pager-bottom");
			List<HtmlAnchor> pagerLinks = marketPagerBottom.getHtmlElementsByTagName("a");
			//logger.info(pagerLinks.toString());
			
			//megkeresni az aktiv link szomszédját
			HtmlAnchor nextAnchor = null;
			for(int i = 0; i < pagerLinks.size(); i++) {
				if(pagerLinks.get(i).getAttribute("class").equals("active-page-link") && i < (pagerLinks.size() - 1)) {
					nextAnchor = pagerLinks.get(i + 1); 
					//logger.info("nextanchor" + nextAnchor.toString());
				}
			}
			if(nextAnchor != null) {
				page = nextAnchor.click();
				webClient.waitForBackgroundJavaScriptStartingBefore(1000);
				readPage(sportId, page, webClient);
			}
		}
	}
}
	
